package websocket

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
	"net/url"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}


func createAcceptor(addr string) (*http.Server, error) {
	urlObj, err := url.Parse(addr)
	if err != nil {
		return nil, fmt.Errorf("websocket urlparse failed. url(%s) %v", addr, err)
	}
	if urlObj.Path == "" {
		return nil, fmt.Errorf("websocket start failed. expect path in url to listen addr:%s", addr)
	}
	LOG.Debugf("startAcceptor path=%v, host=%v", urlObj.Path, urlObj.Host)
	http.HandleFunc(urlObj.Path, wsHandler)
	srv := &http.Server{Addr: urlObj.Host, Handler: nil}
	return srv, nil
}

func wsHandler(w http.ResponseWriter, r *http.Request) {
	var(
		wsConn *websocket.Conn
		err error
	)
	// 完成ws协议的握手操作
	// Upgrade:websocket
	if wsConn , err = upgrader.Upgrade(w,r,nil); err != nil{
		LOG.Debug("upgrader.Upgrade err = ", err)
		return
	}

	LOG.Debug("wsHandler")


	fd := _sessionMgr.GenerateFd()
	conn := newConnection(wsConn, fd, _sessionMgr.MessagePool)
	sess := newWsSession(fd, conn)
	_sessionMgr.AddSession(sess)

	// 启动线程，不断发消息
	//go func(){
	//	for{
	//		conn.WriteMessage([]byte("heartbeat"))
	//		time.Sleep(3*time.Second)
	//	}
	//}()
}


